package jay.home.bet.job;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimerTask;

import jay.home.bet.domain.Comp;
import jay.home.bet.domain.Daxiao;
import jay.home.bet.domain.Duying;
import jay.home.bet.domain.Event;
import jay.home.bet.domain.League;
import jay.home.bet.domain.Rangqiu;
import jay.home.bet.domain.Team;
import jay.home.bet.domain.logic.BasicService;
import jay.home.bet.domain.logic.OddsService;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.spowin.Mansion88.MansionDSpojo;
import com.spowin.Mansion88.Util;

public class Bot extends TimerTask
{
	protected final Log logger = LogFactory.getLog(getClass());
	private OddsService oddsService;
	private BasicService basicService;
	
	static final String LOGON_SITE = "www.mansion88.com";

	static final int LOGON_PORT = 80;
	
	static HttpClient hc = new HttpClient();
	static
	{
		
		hc.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT, "http");

		hc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

		HttpMethod get = new GetMethod();

		try
		{
			hc.executeMethod(get);
		} catch (HttpException e)
		{
			e.printStackTrace();
		} catch (IOException e)
		{
			e.printStackTrace();
		}
		// System.out.println(get.getResponseBodyAsString());
		get.releaseConnection();
	}
	public void run()
	{
		HttpMethod get3 = new GetMethod(
				"/OddsDisplay/MemberOdds/hdpdata.asp");

		try
		{
			hc.executeMethod(get3);
//			System.out.println(get3.getResponseBodyAsString());
			InputStream is = get3.getResponseBodyAsStream();
			InputStreamReader isr = new InputStreamReader(is);

//		 System.out.println(get3.getResponseBodyAsString());

		BufferedReader br = new BufferedReader(isr);
		String nn = new String();

		List<String> value = new ArrayList<String>();

		while(!(nn = br.readLine()).equals("*/"))//由于返回的html代码里面前面很多是不重要的
			logger.debug("读取行....\n" + nn);
		while ((nn = br.readLine())!=null)
		{
			value.add(nn);
			logger.debug("读取行....\n" + nn);

		}
		List<MansionDSpojo> result = new ArrayList<MansionDSpojo>();

		String totalPage = (value.get(4).toString()).split(",")[0].substring(7,
				8);
		String nowPage = (value.get(4).toString()).split(",")[1]
				.substring(1, 2);
		// System.out.println(totalPage);

		// System.out.println(nowPage);
		int tp = Integer.parseInt(totalPage);
		int np = Integer.parseInt(nowPage);

		for (int i = 5; i < value.size() - 7; i++) {
			MansionDSpojo po = Util.getMainsionDSpojo(value.get(i).toString());

			result.add(po);
		}

		while (np + 1 <= tp) {
			HttpMethod get4 = new GetMethod(
			"/OddsDisplay/MemberOdds/hdpdata.asp?sport=0&hdpver=2&ViewType=ah&PageNo="+(np+1)+"&Uid=0.5751101252055805&timer=26487609&TypeNo=1&LeagueCode=");
			
			
			hc.executeMethod(get4);

			// System.out.println(get3.getResponseBodyAsString());

			InputStream is1 = get4.getResponseBodyAsStream();

			InputStreamReader isr1 = new InputStreamReader(is1);

			BufferedReader br1 = new BufferedReader(isr1);
			String nn1 = new String();

			List<String> value1 = new ArrayList<String>();

			while (nn1 != null) {
				nn1 = br1.readLine();
				value1.add(nn1);

			}
			
			for (int i = 5; i < value1.size() - 7; i++) {
				MansionDSpojo po = Util.getMainsionDSpojo(value1.get(i).toString());

				result.add(po);
			}
			np++;
			get4.releaseConnection();
		}
		process(result);
		get3.releaseConnection();
		
		} catch (HttpException e)
		{
			logger.fatal("网络异常, 不能得到接水数据");
			e.printStackTrace();
		} catch (IOException e)
		{
			logger.fatal("IO异常, 不能正确读取得到的接水数据");
			e.printStackTrace();
		}
	}
	private Map<String, MansionDSpojo> odds = new HashMap<String, MansionDSpojo>();
	private void process(List<MansionDSpojo> oddsList)
	{
		Map<String, Integer> counter = new HashMap<String , Integer>();
		for(MansionDSpojo item : oddsList)
		{
			String itemid = item.getGameId();
			logger.debug("获得并预处理赛事 ---> id=" + itemid + "  主队名=" + item.getHomeTeamName() + "  客队名=" + item.getCustTeamName());
			if (counter.get(itemid) == null)counter.put(itemid, 0);
			else counter.put(itemid, counter.get(itemid) + 1);
			item.setGameId(itemid + "_" + counter.get(itemid));
			item.setCustTeamName(trim(item.getCustTeamName()));
			item.setHomeTeamName(trim(item.getHomeTeamName()));
			item.setLeageNameFull(trim2(item.getLeageNameFull()));
		}
		for(MansionDSpojo item : oddsList)
		{
			String itemid = item.getGameId();
			MansionDSpojo m = odds.get(itemid);
			if(m == null)
			{
				odds.put(itemid, item);
				store(item);
				continue;
			}
			if(!noChange(item, odds.get(itemid)))
			{
				odds.put(itemid, item);
				update(item);
				continue;
			}
		}
	}
	

	/**将item更新到数据库*/
	private void update(MansionDSpojo item)
	{
		Event event = oddsService.getEvent(item.getGameId());
		if(event == null)
		{
			logger.warn("bot需要更新赛事, 但是数据库中无此赛事:" + item.getGameId());
			return;
		}
		//半全场大小数据
		event.getDaxiao().setHome(jay.home.bet.misc.Util.toDouble(item.getDaQiuFullTime()));
		event.getDaxiao().setRoad(jay.home.bet.misc.Util.toDouble(item.getXiaoQiuFullTime()));
		event.getDaxiao().setPankou(item.getHkDaXiaoPanKouFullTime());
		event.getDaxiaoHalf().setHome(jay.home.bet.misc.Util.toDouble(item.getDaQiuHalfTime()));
		event.getDaxiaoHalf().setRoad(jay.home.bet.misc.Util.toDouble(item.getXiaoQiuHalfTime()));
		event.getDaxiaoHalf().setPankou(item.getHkDaXiaoPanKouHalfTime());
		
		//半全场让球数据
		event.getRangqiu().setHome(jay.home.bet.misc.Util.toDouble(item.getShangPanFullTime()));
		event.getRangqiu().setRoad(jay.home.bet.misc.Util.toDouble(item.getXiaPanFullTime()));
		event.getRangqiu().setPankou(item.getHkRangQiuPanKouFullTime());
		event.getRangqiu().setWho2who("true".equalsIgnoreCase(item.getRangQiuFlag())?"主让客":"客让主");
		event.getRangqiuHalf().setHome(jay.home.bet.misc.Util.toDouble(item.getShangPanHalfTime()));
		event.getRangqiuHalf().setRoad(jay.home.bet.misc.Util.toDouble(item.getXiaPanHalfTime()));
		event.getRangqiuHalf().setPankou(item.getHkRangQiuPanKouHalfTime());
		event.getRangqiuHalf().setWho2who("true".equalsIgnoreCase(item.getRangQiuFlag())?"主让客":"客让主");
		
		//半全场独赢数据
		event.getDuying().setWin(jay.home.bet.misc.Util.toDouble(item.getHomeTeamWinFullTime()));
		event.getDuying().setDraw(jay.home.bet.misc.Util.toDouble(item.getHomeTeamDrawFullTime()));
		event.getDuying().setLose(jay.home.bet.misc.Util.toDouble(item.getHomeTeamLoseFullTime()));
		event.getDuyingHalf().setWin(jay.home.bet.misc.Util.toDouble(item.getHomeTeamWinHalfTime()));
		event.getDuyingHalf().setDraw(jay.home.bet.misc.Util.toDouble(item.getHomeTeamDrawHalfTime()));
		event.getDuyingHalf().setLose(jay.home.bet.misc.Util.toDouble(item.getHomeTeamLoseHalfTime()));
		
		
		//更新数据到数据库
		oddsService.updateEvent(event);
	}

//	判断item的值和md的值是否相等, 如果是,返回true.这里只判断大小,让球和独赢.
	private boolean noChange(MansionDSpojo item, MansionDSpojo md)
	{
//		大小
		if(!item.getDaQiuFullTime().equals( md.getDaQiuFullTime()))return false;
		if(!item.getDaQiuHalfTime().equals( md.getDaQiuHalfTime()))return false;
		if(!item.getXiaoQiuFullTime().equals( md.getXiaoQiuFullTime()))return false;
		if(!item.getXiaoQiuHalfTime().equals( md.getXiaoQiuHalfTime()))return false;
		if(!item.getHkDaXiaoPanKouFullTime().equals( md.getHkDaXiaoPanKouFullTime()))return false;
		if(!item.getHkDaXiaoPanKouHalfTime().equals( md.getHkDaXiaoPanKouHalfTime()))return false;
		
//		让球
		if(!item.getShangPanFullTime().equals( md.getShangPanFullTime()))return false;
		if(!item.getShangPanHalfTime().equals( md.getShangPanHalfTime()))return false;
		if(!item.getXiaPanFullTime().equals( md.getXiaPanFullTime()))return false;
		if(!item.getXiaPanHalfTime().equals( md.getXiaPanHalfTime()))return false;
		if(!item.getHkRangQiuPanKouFullTime().equals( md.getHkRangQiuPanKouFullTime()))return false;
		if(!item.getHkRangQiuPanKouHalfTime().equals( md.getHkRangQiuPanKouHalfTime()))return false;
		if(!item.getRangQiuFlag().equals( md.getRangQiuFlag()))return false;
		
//		独赢
		if(!item.getHomeTeamWinFullTime().equals( md.getHomeTeamWinFullTime()))return false;
		if(!item.getHomeTeamWinHalfTime().equals( md.getHomeTeamWinHalfTime()))return false;
		if(!item.getHomeTeamDrawFullTime().equals( md.getHomeTeamDrawFullTime()))return false;
		if(!item.getHomeTeamDrawHalfTime().equals( md.getHomeTeamDrawHalfTime()))return false;
		if(!item.getHomeTeamLoseFullTime().equals( md.getHomeTeamLoseFullTime()))return false;
		if(!item.getHomeTeamLoseHalfTime().equals( md.getHomeTeamLoseHalfTime()))return false;
		
		return true;
	}

	/**将item保存到数据库中去*/
	private void store(MansionDSpojo item)
	{
		if(oddsService.getEvent(item.getGameId()) != null)return;
		Event event = new Event();
		Daxiao dx = event.getDaxiao();
		Daxiao dxhalf = event.getDaxiaoHalf();
		Rangqiu rq = event.getRangqiu();
		Rangqiu rqhalf = event.getRangqiuHalf();
		Duying dy = event.getDuying();
		Duying dyhalf = event.getDuyingHalf();
		
		event.setType("单式");
		event.setAcceptBot(true);
		event.setAlive(true);
		event.setFrozen(false);
		event.setPublished(true);
		event.setId(item.getGameId());
		
		dx.setHome(jay.home.bet.misc.Util.toDouble(item.getDaQiuFullTime()));
		dx.setRoad(jay.home.bet.misc.Util.toDouble(item.getXiaoQiuFullTime()));
		dx.setPankou(item.getHkDaXiaoPanKouFullTime());
		dxhalf.setHome(jay.home.bet.misc.Util.toDouble(item.getDaQiuHalfTime()));
		dxhalf.setRoad(jay.home.bet.misc.Util.toDouble(item.getXiaoQiuHalfTime()));
		dxhalf.setPankou(item.getHkDaXiaoPanKouHalfTime());
		
		rq.setHome(jay.home.bet.misc.Util.toDouble(item.getShangPanFullTime()));
		rq.setRoad(jay.home.bet.misc.Util.toDouble(item.getXiaPanFullTime()));
		rq.setPankou(item.getHkRangQiuPanKouFullTime());
		rq.setWho2who("true".equalsIgnoreCase(item.getRangQiuFlag())?"主让客":"客让主");
		rqhalf.setHome(jay.home.bet.misc.Util.toDouble(item.getShangPanHalfTime()));
		rqhalf.setRoad(jay.home.bet.misc.Util.toDouble(item.getXiaPanHalfTime()));
		rqhalf.setPankou(item.getHkRangQiuPanKouHalfTime());
		rqhalf.setWho2who("true".equalsIgnoreCase(item.getRangQiuFlag())?"主让客":"客让主");
		
		dy.setWin(jay.home.bet.misc.Util.toDouble(item.getHomeTeamWinFullTime()));
		dy.setDraw(jay.home.bet.misc.Util.toDouble(item.getHomeTeamDrawFullTime()));
		dy.setLose(jay.home.bet.misc.Util.toDouble(item.getHomeTeamLoseFullTime()));
		dyhalf.setWin(jay.home.bet.misc.Util.toDouble(item.getHomeTeamWinHalfTime()));
		dyhalf.setDraw(jay.home.bet.misc.Util.toDouble(item.getHomeTeamDrawHalfTime()));
		dyhalf.setLose(jay.home.bet.misc.Util.toDouble(item.getHomeTeamLoseHalfTime()));
		
		League league = basicService.getLeague(item.getLeageNameFull());
		if(league == null)league = storeLeague(item.getLeageNameFull());
		Team home = basicService.getTeam(item.getHomeTeamName()); 
		if(home == null)home = storeTeam(item.getHomeTeamName(), league.getId());
		Team road = basicService.getTeam(item.getCustTeamName());
		if(road == null)road = storeTeam(item.getCustTeamName(), league.getId());
		String time = parseTime(item.getGameDate(), item.getGameTime());
		Comp comp = basicService.getCompByDetail(home.getId(), road.getId(), time);
		if(comp == null)comp = storeComp(home, road, league, time);
		
		event.setComp(comp);
		event.setDaxiao(dx);
		event.setDaxiaoHalf(dxhalf);
		event.setRangqiu(rq);
		event.setRangqiuHalf(rqhalf);
		event.setDuying(dy);
		event.setDuyingHalf(dyhalf);
		
		oddsService.insertEvent(event);
	}

	private League storeLeague(String l)
	{
		League league = new League();
		league.setId(l);
		league.setName_en(l);
		league.setName_tw(l);
		league.setName_zh(l);
		basicService.insertLeague(league);
		return basicService.getLeague(league.getId());
	}

	private Comp storeComp(Team home, Team road, League league, String time)
	{
		Comp comp = new Comp();
		comp.setId(jay.home.bet.misc.Util.uuid());
		comp.setHome(home);
		comp.setRoad(road);
		comp.setLeague(league);
		comp.setTime(jay.home.bet.misc.Util.string2Date(time));
		comp.setAlive(true);
		logger.info("bot检测到新赛事(id=" + comp.getId() +"), 自动保存到数据库中.....");
		basicService.insertComp(comp);
		return basicService.getComp(comp.getId());
	}

	private Team storeTeam(String t, String league)
	{
		Team team = new Team();
		team.setId(t);
		team.setName_en(t);
		team.setName_tw(t);
		team.setName_zh(t);
		team.setLeagueid(league);
		logger.info("bot检测到新球队(id=" + team.getId() +"), 自动保存到数据库中.....");
		basicService.insertTeam(team);
		return basicService.getTeam(t);
	}

	/**如->date="02/04"  time="5:10AM", 结果应该为2007-02-04 5:10:00*/
	private String parseTime(String date, String time)
	{
		DateFormat f = new SimpleDateFormat("dd/MM h:mma", Locale.US);
		Date dt = null;
		try
		{
			dt = f.parse(date + " " + time);
		} catch (ParseException e)
		{
			logger.warn("解析时间出错, 时间 : " + date + " " + time + " 模板 : dd/MM h:mma");
			e.printStackTrace();
		}
		dt.setYear(new Date().getYear());
		return jay.home.bet.misc.Util.date2String(dt);
	}
	
	public static void main(String[] args)
	{
		System.out.println(new Bot().parseTime("02/04" , "5:10AM"));
	}

	/**如果en为 "Southampton (H)", 则去掉"(H)", 并去掉首尾字符*/
	private String trim(String target)
	{
		return target.split("\\(.+")[0].trim();
	}
	
	private String trim2(String league)
	{
		if(league.contains("(") && league.contains(")"))
			return league.substring(league.indexOf("(") + 1, league.indexOf(")"));
		return league;
	}
	
	
	
/*===============================setter/getter======================================*/
	public OddsService getOddsService()
	{
		return oddsService;
	}

	public void setOddsService(OddsService oddsService)
	{
		this.oddsService = oddsService;
	}

	public BasicService getBasicService()
	{
		return basicService;
	}

	public void setBasicService(BasicService basicService)
	{
		this.basicService = basicService;
	}
}